package com.starnet.yarnmonitor.yarn.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.starnet.yarnmonitor.yarn.entity.UpgradeJar;
import com.starnet.yarnmonitor.yarn.service.UpgradeJarService;
import com.starnet.yarnmonitor.yarn.utils.PageUtils;
import com.starnet.yarnmonitor.yarn.vo.result.PageResult;
import com.starnet.yarnmonitor.yarn.vo.result.Result;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;


@Log4j
@RestController
@RequestMapping("/upgrade")
public class UpgradeController {
    @Autowired
    UpgradeJarService upgradeJarService;
    @Autowired
    Environment environment;


    @Transactional
    @PostMapping("/upload")
    public Result upload(@RequestPart MultipartFile multipartFile) throws IOException {
        boolean success = upgradeJarService.uploadUpgradeJar(multipartFile);
        if (!success){
            return Result.fail("未知错误");
        }else {
            return Result.success();
        }
    }

    /***
     * 查询已经上传的jar包
     */
    @GetMapping("/jars")
    public PageResult getJarList(@RequestParam(value = "cur", required = false) Integer cur, @RequestParam(value = "size", required = false) Integer size) {
        Page<UpgradeJar> upgradeJarPage = new Page<>();
        if (cur != null) {
            upgradeJarPage.setCurrent(cur);
        }
        if (size != null) {
            upgradeJarPage.setSize(size);
        }

        Page<UpgradeJar> page = upgradeJarService.page(upgradeJarPage);
        return PageResult.success(page.getRecords(), PageUtils.getPageVOFromIPage(page));
    }

    @PostMapping
    public Result upgrade(@RequestParam(value = "id", required = true) Integer id) throws IOException {
        boolean success = upgradeJarService.upgradeById(id);
        if (!success){
            return Result.fail("未知错误");
        }else {
            return Result.success();
        }
    }
    @GetMapping("/version")
    public Result versionNow(){
        return Result.success(environment.getProperty("version"));
    }


}
